<?php

namespace app\admin\controller\auth;

use app\common\controller\BaseAdminController;
use think\exception\ValidateException;
use think\facade\Db;

class Group extends BaseAdminController
{
    protected $groupList = [];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\AuthGroup();
        $list = $this->model->where('status',1)->select()->toArray();

        foreach ($list as $k=>&$v){
            $v['label'] = __($v['name']);
            $v['value'] = $v['id'];
        }
        unset($v);
        $list = list_to_tree($list, 'id', 'pid', 'children');
        $this->groupList = $list;
    }
    public function index()
    {
        if($this->request->isAjax()){
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            return json(['rows'=>$this->groupList,'total'=>count($this->groupList)]);
        }
        return $this->view->fetch();
    }

    /**
     * 获取用户组
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_pids()
    {
        $group = Db::name('auth_group_access')->where('uid',$this->auth->id)->find();
        if(empty($group)){
            return $this->json_error();
        }
        $list = $this->model->where('status',1)->select()->toArray();
        foreach ($list as $k=>&$v){
            $v['label'] = __($v['name']);
            $v['value'] = $v['id'];
        }
        unset($v);
        $mygroup = $this->model->where('id',$group['group_id'])->select()->toArray();
        $mygroup[0]['label'] = __($mygroup[0]['name']);
        $mygroup[0]['value'] = $mygroup[0]['id'];
        $list = list_to_tree($list, 'id', 'pid', 'children',$group['group_id']);
        $mygroup[0]['children'] = $list;
        return $this->json_success($mygroup);
    }
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if(isset($params['pid'])){
                    if(is_array($params['pid'])){
                        $params['pid'] = $params['pid'][count($params['pid'])-1];
                    }
                }
                if(isset($params['rules'])){
                    if(is_array($params['rules'])){
                        $params['rules'] = implode(',',$params['rules']);
                    }
                }
                $result = false;
                Db::startTrans();

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    $result = $this->model->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("添加成功");
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();

    }
}